package com.uduemc.biso.node.web.component.html;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.HtmlUtils;

import com.uduemc.biso.node.core.common.dto.information.InformationTitleItem;
import com.uduemc.biso.node.core.common.sysconfig.InformationSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.informationsysconfig.InformationSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.informationsysconfig.InformationSysListTextConfig;
import com.uduemc.biso.node.core.common.udinpojo.PagingData;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SInformationItem;
import com.uduemc.biso.node.core.entities.SInformationTitle;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.entities.custom.InformationList;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.information.InformationItem;
import com.uduemc.biso.node.core.entities.custom.information.InformationTitleFileConf;
import com.uduemc.biso.node.core.entities.custom.information.InformationTitleImageConf;
import com.uduemc.biso.node.core.utils.InformationTitleConfigUtil;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.html.common.HCPagingUdin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

@Component
public class HSystemInformationItemListUdin {

	private static String name = "system_information_item_list";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private HCPagingUdin hCPagingUdin;

	public StringBuilder html(SSystem system, SPage page, InformationList informationList, List<InformationTitleItem> listInformationTitleItem, int pageNum)
			throws IOException {
		if (system == null || page == null) {
			return new StringBuilder("<!-- PLComp empty informationSystem -->\n");
		}
		// 获取系统配置
		InformationSysConfig informationSysConfig = SystemConfigUtil.informationSysConfig(system);
		InformationSysListConfig list = informationSysConfig.getList();
		InformationSysListTextConfig ltext = informationSysConfig.getLtext();
		int showlistdata = list.getShowlistdata();
		int perpage = list.getPerpage();

		int tablestyle = list.getTablestyle();
		String pagewidth = list.getPagewidth();

		// 生成html渲染内容
		StringBuilder stringBuilder = new StringBuilder("<!-- PLComp -->\n");

		List<SInformationTitle> title = informationList.getTitle();
		List<InformationItem> rows = informationList.getRows();
		long total = informationList.getTotal();
		boolean showdata = false;
		if (CollUtil.isEmpty(listInformationTitleItem)) {
			if (showlistdata == 1) {
				// 展示信息数据
				showdata = true;
			}
		} else {
			showdata = true;
		}
		String inputHtml = inputHtml(title, listInformationTitleItem, rows, informationSysConfig);
		String pagewidthScript = pagewidthScript(pagewidth);
		String informationScript = informationScript(informationSysConfig);
		String tableTheadTrThHtml = showdata ? tableTheadTrThHtml(title) : "";
		String tableTbodyTrHtml = showdata ? tableTbodyTrHtml(title, rows, informationSysConfig) : "";
		// 分页部分
		String listHref = siteUrlComponent.getListHref(page, null, "[page]", "");
		PagingData pagingData = ltext.getPagingData();
		int pageTotal = (int) Math.ceil((double) total / (double) perpage);
		// pagging
		StringBuilder pagging = hCPagingUdin.html(listHref, pageNum, pageTotal, pagingData);

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("showdata", showdata);
		mapData.put("inputHtml", inputHtml);
		mapData.put("tableTheadTrThHtml", tableTheadTrThHtml);
		mapData.put("tableTbodyTrHtml", tableTbodyTrHtml);
		mapData.put("pagging", pagging.toString());
		mapData.put("pagewidthScript", pagewidthScript);
		mapData.put("informationScript", informationScript);
		StringWriter render = basicUdin.render(name, "default_" + tablestyle, mapData);
		stringBuilder.append(render);

		return stringBuilder;
	}

	protected String tableTbodyTrHtml(List<SInformationTitle> title, List<InformationItem> rows, InformationSysConfig informationSysConfig) {
		InformationSysListTextConfig ltext = informationSysConfig.getLtext();
		String noData = ltext.getNoData();

		StringBuilder stringBuilder = new StringBuilder();
		if (CollUtil.isEmpty(rows)) {
			int colspan = 0;
			for (SInformationTitle sInformationTitle : title) {
				if (sInformationTitle.getStatus().shortValue() != (short) 1) {
					continue;
				}
				colspan++;
			}
			stringBuilder.append("<tr><td colspan=\"" + colspan + "\">&nbsp;&nbsp;&nbsp;&nbsp;" + HtmlUtils.htmlEscape(noData) + "</td></tr>");
		} else {
			for (InformationItem informationItem : rows) {
				stringBuilder.append("<tr>");
				for (SInformationTitle sInformationTitle : title) {
					if (sInformationTitle.getStatus().shortValue() != (short) 1) {
						continue;
					}
					StringBuilder tdTag = informationSystemItemHtml(sInformationTitle, informationItem);
					stringBuilder.append(tdTag);
				}
				stringBuilder.append("</tr>");
			}
		}

		return stringBuilder.toString();
	}

	protected String tableTheadTrThHtml(List<SInformationTitle> title) {
		StringBuilder stringBuilder = new StringBuilder();

		for (SInformationTitle sInformationTitle : title) {
			if (sInformationTitle.getStatus().shortValue() != (short) 1) {
				continue;
			}
			Long id = sInformationTitle.getId();
			String thTitle = sInformationTitle.getTitle();
			String proportion = StrUtil.trim(sInformationTitle.getProportion());
			String width = "";
			if (StrUtil.isNotBlank(proportion) && !proportion.equals("-1")) {
				width = "width=\"" + proportion + "%\"";
			}
			stringBuilder.append("<th class=\"\" " + width + " data-titleid=\"" + id + "\">" + HtmlUtils.htmlEscape(thTitle) + "</th>");
		}

		return stringBuilder.toString();
	}

	protected StringBuilder informationSystemItemHtml(SInformationTitle sInformationTitle, InformationItem informationItem) {
		List<SInformationItem> listItem = informationItem.getListItem();
		RepertoryQuote image = informationItem.getImage();
		RepertoryQuote file = informationItem.getFile();

		StringBuilder stringBuilder = new StringBuilder();
		Short type = sInformationTitle.getType();
		if (type == null) {
			stringBuilder.append("<td></td>");
		}

		if (type.shortValue() == (short) 1) {
			Optional<SInformationItem> findFirst = listItem.stream().filter(item -> {
				return item.getInformationTitleId().longValue() == sInformationTitle.getId().longValue();
			}).findFirst();
			if (findFirst.isPresent()) {
				SInformationItem sInformationItem = findFirst.get();
				String value = StrUtil.trim(sInformationItem.getValue());
				value = StrUtil.isNotBlank(value) ? HtmlUtils.htmlEscape(value) : value;
				if (StrUtil.isBlank(value)) {
					stringBuilder.append("<td><!-- value is blank --></td>");
				} else {
					stringBuilder.append("<td>" + value + "</td>");
				}
			} else {
				stringBuilder.append("<td><!-- no value --></td>");
			}
		} else if (type.shortValue() == (short) 2) {
			if (image == null || image.getHRepertory() == null) {
				stringBuilder.append("<td><!-- no image --></td>");
			} else {
				HRepertory hRepertory = image.getHRepertory();
				String imgSrc = siteUrlComponent.getImgSrc(hRepertory);
				String hRepertoryMdId = SecureUtil.md5(String.valueOf(hRepertory.getId()));
				InformationTitleImageConf imageConf = InformationTitleConfigUtil.imageConf(sInformationTitle);
				String tdText = imageConf.getTdText();
				tdText = StrUtil.isNotBlank(tdText) ? HtmlUtils.htmlEscape(tdText) : tdText;

				String aImgTag = "<a style=\"cursor:pointer;\" data-alt=\"\" class=\"fancybox-thumbs\" href=\"" + imgSrc + "\" data-lightbox=\"image-"
						+ hRepertoryMdId + "\">" + tdText + "</a>";

				stringBuilder.append("<td>" + aImgTag + "</td>");
			}
		} else if (type.shortValue() == (short) 3) {
			if (file == null || file.getHRepertory() == null) {
				stringBuilder.append("<td><!-- no file --></td>");
			} else {
				HRepertory hRepertory = file.getHRepertory();
				String downloadHref = siteUrlComponent.getDownloadHref(hRepertory.getId());
				InformationTitleFileConf fileConf = InformationTitleConfigUtil.fileConf(sInformationTitle);
				int fileConfType = fileConf.getType();
				String tdText = fileConf.getTdText();
				String obText = fileConf.getObText();
				tdText = StrUtil.isNotBlank(tdText) ? HtmlUtils.htmlEscape(tdText) : "";
				obText = StrUtil.isNotBlank(obText) ? HtmlUtils.htmlEscape(obText) : "";

				String suffix = hRepertory.getSuffix();
				String iconClass = HSystemDownloadItemListUdin.getIconClassMap(suffix);

				String iHtml = "";
				if (fileConfType == 1) {
					iHtml = "<i class=\"" + iconClass + "\"></i>";
				} else {
					iHtml = tdText;
				}

				String aDownloadTag = "";
				if (suffix.toLowerCase().equals("pdf")) {
					String onlineBrowseHref = siteUrlComponent.getPreviewPdfHref(hRepertory.getOriginalFilename(), hRepertory.getId());
					if (fileConfType == 1) {
						aDownloadTag += "<a style=\"cursor:pointer;\" target=\"_blank\" class=\"fancybox-thumbs\" href=\"" + onlineBrowseHref
								+ "\" ><img style=\"width: 25px;height: 25px;\" src=\"/assets/static/site/np_template/images/icon_preview1.png\" /></a>&nbsp;&nbsp;";
					} else {
						aDownloadTag += "<a style=\"cursor:pointer;\" target=\"_blank\" class=\"fancybox-thumbs\" href=\"" + onlineBrowseHref + "\" >" + obText
								+ "</a>&nbsp;&nbsp;";
					}
				}

				aDownloadTag += "<a style=\"cursor:pointer;\" target=\"_blank\" class=\"fancybox-thumbs\" href=\"" + downloadHref + "\" >" + iHtml + "</a>";
				stringBuilder.append("<td>" + aDownloadTag + "</td>");
			}
		} else {
			stringBuilder.append("<td></td>");
		}
		return stringBuilder;
	}

	protected String inputHtml(List<SInformationTitle> title, List<InformationTitleItem> listInformationTitleItem, List<InformationItem> rows,
			InformationSysConfig informationSysConfig) {
		InformationSysListTextConfig ltext = informationSysConfig.getLtext();
		String searchButtonText = ltext.getSearchButtonText();

		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<div class=\"msgLBox g-info-search\">");
		for (SInformationTitle sInformationTitle : title) {
			if (sInformationTitle.getType().shortValue() != (short) 1 && sInformationTitle.getStatus().shortValue() != (short) 1) {
				continue;
			}

			if (sInformationTitle.getSiteSearch().shortValue() == (short) 1) {
				Long titleId = sInformationTitle.getId();
				String searchTitle = sInformationTitle.getTitle();
				Short siteRequired = sInformationTitle.getSiteRequired();
				String placeholder = sInformationTitle.getPlaceholder();
				placeholder = StrUtil.isNotBlank(placeholder) ? HtmlUtils.htmlEscape(placeholder) : placeholder;
				Optional<InformationTitleItem> findFirst = listInformationTitleItem.stream().filter(item -> {
					return item.getInformationTitleId() == titleId.longValue();
				}).findFirst();
				String value = findFirst.isPresent() ? findFirst.get().getValue() : "";
//				value = StrUtil.isNotBlank(value) ? HtmlUtils.htmlEscape(value) : value;
				String searchRequiredHtml = siteRequired.shortValue() == (short) 1 ? "<span class=\"star\">*</span>" : "";

				stringBuilder.append("<dl class=\"clearfix\">");
				stringBuilder.append("<dd class=\"dl_ddL\" title=\"" + HtmlUtils.htmlEscape(searchTitle) + "\">" + HtmlUtils.htmlEscape(searchTitle)
						+ searchRequiredHtml + "</dd>");
				stringBuilder.append("<dd class=\"dl_ddR\">");
				stringBuilder.append("<input class=\"w-text-form\" placeholder=\"" + placeholder + "\" data-required=\"" + siteRequired + "\" data-titleid=\""
						+ titleId + "\" value=\"" + value + "\" type=\"text\">");
				stringBuilder.append("</dd>");
				stringBuilder.append("</dl>");
			}

		}

		stringBuilder.append("<dl class=\"clearfix\">");
		stringBuilder.append("<dd class=\"dl_ddL\"></dd>");
		stringBuilder.append("<dd class=\"dl_ddR\">");
		stringBuilder.append("<div class=\"w-form-submit\">");
		stringBuilder.append("<div class=\"w-buttom\">");
		stringBuilder
				.append("<div class=\"btn-default-w g-form-info\"> <span class=\"btn-inner\">" + HtmlUtils.htmlEscape(searchButtonText) + "</span> </div>");
		stringBuilder.append("</div>");
		stringBuilder.append("</div>");
		stringBuilder.append("</dd>");
		stringBuilder.append("</dl>");
		stringBuilder.append("</div>");

		return stringBuilder.toString();
	}

	protected String pagewidthScript(String pagewidth) {
		StringBuilder stringBuilder = new StringBuilder();
		if (StrUtil.isBlank(pagewidth)) {
			return stringBuilder.toString();
		}
		Map<String, Object> mapData = new HashMap<>();
		mapData.put("pagewidth", pagewidth);
		StringWriter render = basicUdin.render(name, "pagewidth_script", mapData);
		stringBuilder.append(render);
		return stringBuilder.toString();
	}

	protected String informationScript(InformationSysConfig informationSysConfig) {
		String titlenotempty = informationSysConfig.getLtext().getTitlenotempty();
		String notallempty = informationSysConfig.getLtext().getNotallempty();
		int showlistdata = informationSysConfig.getList().getShowlistdata();
		StringBuilder stringBuilder = new StringBuilder();
		Map<String, Object> mapData = new HashMap<>();
		mapData.put("showlistdata", showlistdata);
		mapData.put("titlenotempty", HtmlUtils.htmlEscape(titlenotempty));
		mapData.put("notallempty", HtmlUtils.htmlEscape(notallempty));
		StringWriter render = basicUdin.render(name, "information_script", mapData);
		stringBuilder.append(render);
		return stringBuilder.toString();
	}

}
